package com.google.code.irouter.portal.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.code.irouter.model.Collector;
import com.google.code.irouter.model.Guide;
import com.google.code.irouter.model.Model;
import com.google.code.irouter.model.Relationship;
import com.google.code.irouter.portal.client.rpc.collector.CollectorResult;
import com.google.code.irouter.portal.client.rpc.collector.CollectorService;
import com.google.code.irouter.portal.client.rpc.guide.GuideResult;
import com.google.code.irouter.utils.ModelUtil;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class CollectorServiceImpl extends RemoteServiceServlet implements CollectorService {

	private static final long serialVersionUID = -5469235514458497221L;

	@Override
	public CollectorResult get(String id) throws IllegalArgumentException {
		CollectorResult result = null;
		try {
			List<Model> relationList = ModelUtil.select(Relationship.class, KeyFactory.createKey(Relationship.class.getSimpleName(), Long.valueOf(id)));
			if(relationList.size() > 0) {
				Key collectorKey = ((Relationship) relationList.get(0)).getCollector();
				List<Model> modelList = ModelUtil.select(Collector.class, collectorKey);
				result = new CollectorResult();
				if(modelList.size() > 0) {
					Collector collector = (Collector) modelList.get(0);
					Set<Key> keySet = collector.getGuides();
					List<GuideResult> guides = new ArrayList<GuideResult>();
					for(Key key : keySet) {
						List<Model> guideList = ModelUtil.select(Guide.class, key);
						if(guideList.size() > 0) {
							Guide guide = (Guide) guideList.get(0);
							GuideResult guideResult = new GuideResult();
							guideResult.setId(guide.getKey().getId());
							guideResult.setName(guide.getName());
							guideResult.setOwner(guide.getOwner());
							guideResult.setResource(guide.getResource().getValue());
							guideResult.setFixedLink(guide.getFixedLink().getValue());
							guideResult.setDetector(GuideServiceImpl.getDetectorName(guide.getDetector()));
							guides.add(guideResult);
						}
					}
					result.setGuides(guides);
				}
			}			
		} catch (Exception exception) {
			// TODO
		}
		return result;
	}
}
